import { loadLocale } from "../utils/locale"

export default defineEventHandler(async (event) => {
  loadLocale(event)
  const cookies = parseCookies(event)
  const token = cookies['auth-token']
  const apiSecurePaths = ['/api/secure/*']
  const routeSecurePaths = ['/secure/*']
  // 检查请求路径是否允许匿名访问
  const isApiSecure = apiSecurePaths.some(path => {
    if (path.endsWith('*')) {
      return event.path.startsWith(path.slice(0, -1))
    }
    return event.path === path
  })
  const isRouteSecure = routeSecurePaths.some(path => {
    if (path.endsWith('*')) {
      return event.path.startsWith(path.slice(0, -1))
    }
    return event.path === path
  })

  if (!token) {
    if (isApiSecure) {
      throw createError({
        statusCode: 401,
        message: '未授权'
      })
    }
    if (isRouteSecure) {
      event.node.res.statusCode = 302
      event.node.res.setHeader('Location', `/login?redirect=${encodeURIComponent(event.path)}`)
      event.node.res.end() 
    }
  }
  
  try {
    const session = await verifyJWT(token)
    event.context.session = session // 将用户信息附加到上下文中
    event.context.cookies = cookies // 将 token 附加到上下文中
  } catch (error) {
    throw createError({
      statusCode: 401,
      message: '无效的 token'
    })
  }
})